#include "preprocess.h"
#include <fstream>

using namespace cv;
using namespace std;

int preprocess(cv::Mat& img, const std::vector<int>& size, float *input) {
    int iw = img.cols;
    int ih = img.rows;
    int w = size[0];
    int h = size[1];

    float scale = std::min(static_cast<float>(w) / iw, static_cast<float>(h) / ih);
    int nw = static_cast<int>(iw * scale);
    int nh = static_cast<int>(ih * scale);

    cv::Mat resized_image;
    cv::resize(img, resized_image, cv::Size(nw, nh), 0, 0, cv::INTER_CUBIC);
    
    cv::Mat new_image(h, w, CV_8UC3, cv::Scalar(128, 128, 128));

    int x_offset = (w - nw) / 2;
    int y_offset = (h - nh) / 2;

    resized_image.copyTo(new_image(cv::Rect(x_offset, y_offset, nw, nh)));

    std::vector<cv::Mat> channels(3);
    cv::split(new_image, channels);

    int idx = 0;
    for (int c = 0; c < 3; ++c) {
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                input[idx++] = channels[c].at<uchar>(i, j) / 255.0f;
            }
        }
    }
    return 0;
}
